package com.yoomiito.app.widget;

import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yoomiito.app.R;
import com.yoomiito.app.listener.OnSelectedChangeListener;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.ColorUtils;
import com.yoomiito.app.utils.DensityUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 分享文案控件
 */
public class ShareDocVIew extends LinearLayout implements OnSelectedChangeListener, View.OnClickListener {

    private Context mContext;
    private TextView contentTv;
    private SelectView sv_1;
    private SelectView sv_2;
    private SelectView sv_3;
    private SelectView sv_4;
    private List<String> docs;
    private boolean[] flags = {true, true, true, true};
    private String str;

    public ShareDocVIew(Context context) {
        this(context, null);
    }

    public ShareDocVIew(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ShareDocVIew(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public ShareDocVIew(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        this.mContext = context;

        init();
    }

    private void init() {
        setBackgroundResource(R.color.color_F4F4F4);
        setOrientation(VERTICAL);
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_share_doc, null);
        addView(view);
        contentTv = view.findViewById(R.id.item_share_doc);
        contentTv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        contentTv.setLongClickable(false);
        contentTv.setOnTouchListener((v, event) -> {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    setSelectHandleDisabled();
                                }
                            }, 50); // 延迟50ms，等room显示handle完后，再隐藏
                            break;
                        default:
                            break;
                    }
                    return super.onTouchEvent(event);
                }
        );
        contentTv.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {

            }
        });
        sv_1 = view.findViewById(R.id.item_share_doc_sv_1);
        sv_2 = view.findViewById(R.id.item_share_doc_sv_2);
        sv_3 = view.findViewById(R.id.item_share_doc_sv_3);
        sv_4 = view.findViewById(R.id.item_share_doc_sv_4);
        Button click = view.findViewById(R.id.item_share_btn);
        click.setOnClickListener(this);
        GradientDrawable drawable = ColorUtils.INSTANCE.gradient("#FF246C","#FF035B",GradientDrawable.Orientation.LEFT_RIGHT);
        drawable.setCornerRadius(DensityUtil.dp2px(23));
        click.setBackground(drawable);
        sv_1.setSelect(true);
        sv_2.setSelect(true);
        sv_3.setSelect(true);
        sv_4.setSelect(true);
        sv_1.setChangeListener(this);
        sv_2.setChangeListener(this);
        sv_3.setChangeListener(this);
        sv_4.setChangeListener(this);

    }


    @Override
    public void change(View view, boolean isSelected) {
        int i = -1;
        switch (view.getId()) {
            case R.id.item_share_doc_sv_1:
                i = 0;
                break;
            case R.id.item_share_doc_sv_2:
                i = 1;
                break;
            case R.id.item_share_doc_sv_3:
                i = 2;
                break;
            case R.id.item_share_doc_sv_4:
                i = 3;
                break;
        }
        if (i == -1) return;
        flags[i] = isSelected;
        setContent();
    }

    public void setText(List<String> strs) {
        if (strs.size() != 7) {
            try {
                throw new IllegalAccessException("文案数量不为7");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        this.docs = strs;
        setContent();
    }

    public void setText(String str) {

    }

    /*
    &#32; == 普通的英文半角空格

    &#160; == &nbsp; == &#xA0; == no-break space （普通的英文半角空格但不换行）

    &#12288; == 中文全角空格 （一个中文宽度）

    &#8194; == &ensp; == en空格 （半个中文宽度）

    &#8195; == &emsp; == em空格 （一个中文宽度）

    &#8197; == 四分之一em空格 （四分之一中文宽度）
     */

    /**
     *
     */
    private void setContent() {
        str = docs.get(0) + "\n" + docs.get(1) + "\n" + docs.get(2);
        if (docs.size() > 3) {
            for (int i = 0; i < flags.length; i++) {
                if (flags[i]) {
                    str = str + "\n" + docs.get(i + 3);
                }
            }
        }
        contentTv.setText(str);
    }

    public String getContent() {
        return str;
    }

    @Override
    public void onClick(View v) {
        AllUtils.copyText(mContext, str);
        Toast.makeText(mContext, "复制成功", Toast.LENGTH_SHORT).show();
    }

    private void setSelectHandleDisabled() {
        try {
            Field mEditor = TextView.class.getDeclaredField("mEditor");
            mEditor.setAccessible(true);
            Object object = mEditor.get(this);
            Class mClass = Class.forName("android.widget.Editor");
            // 选中时handle
            Method selectionController = mClass.getDeclaredMethod("getSelectionController");
            selectionController.setAccessible(true);
            Object invokeSelect = selectionController.invoke(object);
            Method hideSelect = invokeSelect.getClass().getDeclaredMethod("hide");
            hideSelect.invoke(invokeSelect);
            // 插入时handle
            Method insertionController = mClass.getDeclaredMethod("getInsertionController");
            insertionController.setAccessible(true);
            Object invokeInsert = insertionController.invoke(object);
            Method hideInsert = invokeInsert.getClass().getDeclaredMethod("hide");
            hideInsert.invoke(invokeInsert);
        } catch (Exception e) {

        }

    }
}
